import requests
from datetime import datetime
from functools import lru_cache
import os
from ctypes import wintypes
import json


class OneDay():

    def __init__(self):
        self.__lat,self.__lon,self.__city =  None,None,None
        self.sunrise = None
        self.sunset = None
        self.now = None
        self.load_config()

    def load_config(self):
        """加载配置"""
        if os.path.exists("./config.json"):
            with open("./config.json","r") as file:
                data = json.load(file)
                self.sunrise = data["sunrise"]
                self.sunset = data["sunset"]
                self.now = data["now"]
        
        else:
            self.__init_file()

    def __get_location(self):
        """获取当前位置
        """
        response = requests.get("http://ip-api.com/json/", timeout=50)
        data = response.json()
        if data["status"] == "success":
            self.__lat,self.__lon,self.__city = data["lat"], data["lon"], data["city"]
        else:
            print("请求超时！检测网络情况！")

    @lru_cache
    def __get_sunrise_sunset(self):
        """获取日出 日落时间

        :return: _description_
        """
        url = f"https://api.sunrise-sunset.org/json?lat={self.__lat}&lng={self.__lon}&date=today&formatted=0"

        response = requests.get(url,timeout=50)
        data = response.json()
        if data["status"] == "OK":
            sunrise_str = data["results"]["sunrise"]  # ISO 8601 UTC
            sunset_str = data["results"]["sunset"]
            
            # 解析 ISO 时间字符串
            sunrise_utc = datetime.fromisoformat(sunrise_str.replace("Z", "+00:00"))
            sunset_utc = datetime.fromisoformat(sunset_str.replace("Z", "+00:00"))

            # 转换为本地时区 24 小时
            sunrise_local = sunrise_utc.astimezone()
            sunset_local = sunset_utc.astimezone()

            # 转换为当天的分钟数  
            self.sunrise = sunrise_local.hour * 60 + sunrise_local.minute
            self.sunset = sunset_local.hour * 60 + sunset_local.minute

            return self.sunrise,self.sunrise

    def __get_json_data(self):
        """获取json数据"""
        json_data =         {
                "sunrise" : self.sunrise,
                "sunset" : self.sunset,
                "now" : self.now
        }
        return  json_data

    def get_current_time(self):
        """获取当前时间
        """
        if self.now:
            return self.now
        else:
            now = datetime.now()
            now_min = now.hour * 60 + now.minute
            self.now = now_min
            return self.now

    def __save_config(self):
        """保存到json
        """
        file_path = ".\\config.json"
        json_data = self.__get_json_data()
        with open(file_path, "w", encoding="utf-8") as file:
            # 使用 json.dumps() 将字典转换为格式化的 JSON 字符串
            json_string = json.dumps(json_data,indent=4, ensure_ascii=False)
            file.write(json_string)

        # 将文件设置为隐藏项
        absolute_path = os.path.abspath(file_path)
        os.system(f'attrib +h "{absolute_path}"')

    def __init_file(self):
        """初始化config"""
        self.__get_location()
        self.__get_sunrise_sunset()
        self.get_current_time()
        self.__save_config()

    def get_sunrise(self):
        """获取日出事件
        """
        return self.sunrise

    def get_sunset(self):
        """获取日落事件
        """
        return self.sunset



